package com.example.NetworkSender.network;

import android.util.Log;

import java.io.PrintWriter;
import java.net.*;

public class NetworkSender implements Runnable {

    public final Object lockObj = new Object();
    private final int port;
    public int[] buffer;
    public int size = 0;
    public boolean hasDataToSend = false;
    public boolean timeToDie = false;
    private InetAddress neighbour;

    public NetworkSender(String address, int port) throws UnknownHostException {
        this.port = port;
        buffer = new int[10];
        neighbour = InetAddress.getByName(address);
    }

    @Override
    public void run() {
        try {

            Socket neighbourSocket = new Socket();
            SocketAddress addr = new InetSocketAddress(neighbour, port);
            neighbourSocket.connect(addr);
            PrintWriter out = new PrintWriter(neighbourSocket.getOutputStream());

            boolean shouldStop = false;

            while (!shouldStop) {
                synchronized (lockObj) {
                    shouldStop = timeToDie;
                    if (hasDataToSend) {
                        out.println(size);
                        for (int i = 0; i < size; i++) {
                            out.println(buffer[i]);
                        }
                    }
                }
                Thread.sleep(200);
            }
        } catch (Exception ex) {
            Log.e("NetworkSender.run", "EXCEPTION  " + ex.getMessage() + "   !");
        }
    }

    public void stop() {
        synchronized (lockObj) {
            timeToDie = true;
        }
    }
}
